package org.cweili.vehicle.service

import org.cweili.vehicle.entity.Journey
import org.cweili.vehicle.util.Const
import org.cweili.vehicle.util.JSON
import org.cweili.vehicle.util.Utils
import org.directwebremoting.annotations.RemoteProxy
import org.directwebremoting.spring.SpringCreator
import org.springframework.data.domain.Page
import org.springframework.data.domain.PageRequest
import org.springframework.data.domain.Sort
import org.springframework.stereotype.Service

import com.alibaba.fastjson.JSONArray


/**
 * 班次服务
 *
 * @author Cweili
 * @version 2013年7月27日 下午11:01:28
 *
 */
@RemoteProxy(creator = SpringCreator.class)
@Service
class JourneyService extends BaseService {

	Page<Journey> getList(String json) {
		def obj = JSON.parseObject(json)

		def verifyStatus = JSON.getByte(obj, "verifyStatus")
		def page = JSON.getInteger(obj, "page")

		if (verifyStatus < 3) {
			return journeyRepository.findByCommitCustomerAndVerifyStatus(getCustomer(), verifyStatus,
			new PageRequest(page, Const.PAGE_SIZE, Sort.Direction.DESC, "id"))
		} else {
			return journeyRepository.findByVerifyStatus(Journey.VERIFY_PASSED, new PageRequest(
			page, Const.PAGE_SIZE, Sort.Direction.DESC, "id"))
		}
	}

	boolean del(String json) {
		try {
			def array = JSONArray.parseArray(json)

			for (obj in array) {
				int id = Utils.parseInt(obj)
				if (1 > id) {
					return false
				}
				def journey = journeyRepository.findOne(id)
				if (journey) {
					if (Journey.VERIFY_PASSED > journey.getVerifyStatus()) {
						journeyRepository.delete(id)
					}
				}
			}
		} catch (Exception e) {
			log.error(e + json, e)
			return false
		}
		return true
	}

	boolean save(String json) {
		def obj = JSON.parseObject(json)

		def id = JSON.getInteger(obj, "id")
		def journeyTime = JSON.getString(obj, "journeyTime")
		def route = JSON.getString(obj, "route")
		def remark = JSON.getString(obj, "remark")

		if (Utils.isEmpty(journeyTime, route)) {
			return false
		}

		def journey
		if (id > 0) {
			journey = journeyRepository.findOne(id)
			if (!journey) {
				return false
			} else if (Journey.VERIFY_PASSED <= journey.getVerifyStatus()) {
				return false
			}
		} else {
			journey = new Journey(commitCustomer : getCustomer())
		}

		journey.journeyTime = journeyTime
		journey.route = route
		journey.remark = remark
		journey.commitDate = new Date()
		journey.verifyStatus = Journey.VERIFY_UNVERIFYED

		return journeyRepository.save(journey)
	}
}
